// local_gpio.cpp
//
// A Rivendell switcher driver for MeasurementComputing GPIO cards.
//
//   (C) Copyright 2002-2003 Fred Gleason <fredg@paravelsystems.com>
//
//      $Id: local_gpio.cpp,v 1.7 2007/09/14 14:06:59 fredg Exp $
//
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 2 as
//   published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
//   You should have received a copy of the GNU General Public
//   License along with this program; if not, write to the Free Software
//   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//

#include <stdlib.h>

#include <globals.h>
#include <local_gpio.h>


LocalGpio::LocalGpio(RDMatrix *matrix,QObject *parent,const char *name)
  : QObject(parent,name)
{
#ifdef HAVE_GPIO
  //
  // Get Matrix Parameters
  //
  gpio_matrix=matrix->matrix();
  gpio_gpis=matrix->gpis();
  gpio_gpos=matrix->gpos();

  //
  // Initialize the card
  //
  gpio_gpio=new RDGpio(this,"gpio_gpio");
  gpio_gpio->setDevice(matrix->gpioDevice());
  if(gpio_open=gpio_gpio->open()) {
    if(gpio_gpis==0) {
      gpio_gpio->setMode(RDGpio::Output);
    }
    if(gpio_gpos==0) {
      gpio_gpio->setMode(RDGpio::Input);
    }
    connect(gpio_gpio,SIGNAL(inputChanged(int,bool)),
	    this,SLOT(inputChangedData(int,bool)));
  }
#endif  // HAVE_GPIO
}


LocalGpio::~LocalGpio()
{
#ifdef HAVE_GPIO
  delete gpio_gpio;
#endif  // HAVE_GPIO
}


void LocalGpio::processCommand(RDMacro *cmd)
{
#ifdef HAVE_GPIO
  switch(cmd->command()) {
      case RDMacro::GO:
	if((!gpio_open)||(cmd->argQuantity()!=4)||
	   (cmd->arg(1).toInt()<1)||(cmd->arg(1).toInt()>gpio_gpos)||
	   ((cmd->arg(2).toInt()!=1)&&(cmd->arg(2).toInt()!=0))||
	   (cmd->arg(3).toInt()<0)) {
	  cmd->acknowledge(false);
	  emit rmlEcho(cmd);
	  return;
	}
	if(cmd->arg(2).toInt()==0) {
	  gpio_gpio->gpoReset(cmd->arg(1).toInt()-1,cmd->arg(3).toInt());
	}
	else {
	  gpio_gpio->gpoSet(cmd->arg(1).toInt()-1,cmd->arg(3).toInt());
	}
	cmd->acknowledge(true);
	emit rmlEcho(cmd);
	break;

      default:
	cmd->acknowledge(false);
	emit rmlEcho(cmd);
	break;
  }
#endif  // HAVE_GPIO
}


void LocalGpio::inputChangedData(int line,bool state)
{
#ifdef HAVE_GPIO
  emit gpiChanged(gpio_matrix,line,state);
#endif  // HAVE_GPIO
}
